//
//  OAuthViewController.swift
//  Weibo
//
//  Created by mac on 16/3/13.
//  Copyright © 2016年 hw.chow. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {

    
    //MARK:关闭页面
    @objc private func close(){
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //设置测试账号
    @objc private func defaultAccount(){
    
        let jsString = "document.getElementById('userId').value = 'chowhw@sina.com',document.getElementById('passwd').value = 'zhu512chow'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    //将webView定义为属性
    let webView = UIWebView()
    
    override func loadView() {
        //将根视图替换为webView
        view = webView
        
        //设置webview的代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //设置导航条
        setNavBar()
        //加载授权页面
        loadOAuthPage()
    }
    
    //设置导航条
    private func setNavBar(){
    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        //设置测试账号
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "defaultAccount")
        
        
    }
    
    //MARK:加载授权页面
    private func loadOAuthPage(){
        
        //1.获取拼接地址
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=3419231638" + "&redirect_uri=http://www.baidu.com"
        //2.可选的url
        let url = NSURL(string: urlString)!
        //3.获取request
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
    }
}
/*
switf中这样写，是将一类协议方法写在一起，便于阅读和维护
同一类的协议方法，放在一个扩展中
*/

extension OAuthViewController:UIWebViewDelegate{

    func webViewDidStartLoad(webView: UIWebView) {
        //显示
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //隐藏
        SVProgressHUD.dismiss()
    }
    
    
    //很重要的方法 主要获取code授权码
    //该方法返回值为Bool类型，返回true表示控件可以正常运行
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //截取url中的code授权码
        
//        print(request.URL?.absoluteString)
        
        guard let urlString = request.URL?.absoluteString else{
            //假如不能获取url的字符串，就直接不加载网页
            return false
        }
        
        if urlString.containsString("code="){
        
            print(urlString)
            
            //将url中的参数获取到
            //假如不能获取query的字符串，就直接返回
            guard let query = request.URL?.query else{
                return false
            }
            
            let codeStr = "code="
            //将query转换成NSString   subString
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            print(code,query)
            
            //调用获取授权的token方法
            loadAccessToken(code)
            
            //不希望页面跳转到 回调页面
            return false
        }
        return true
    }
    
    //调用
    private func loadAccessToken(code:String){
        
        //请求token和用户信息
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            if !isSuccess {
                print("用户登录失败")
                SVProgressHUD.showErrorWithStatus("网络君正在休息")
                return
            }
            
            //一定登陆成功
            SVProgressHUD.showSuccessWithStatus("登录成功")
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
 

}